<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <!--title-->
      <el-row>
        <el-col :span="12">
          <e-heading style="margin-top:0;" :grade="'1'">{{$route.query.id ? '编辑' : '新增'}}训练方式</e-heading>
        </el-col>
      </el-row>
      <!--form-->
      <el-form ref="form" :model="form" class="addmode_form" v-bind="getFormProps()">
        <!--rules推荐写在html结构-->
        <el-form-item label="运动类型："
          prop="sportType"
          :rules="[{type: 'number', required: true, message: '请选择运动类型', trigger: 'change'}]">
          <el-select v-model="form.sportType" placeholder="请选择运动类型">
            <el-option
              v-for="item in mode_sport_list"
              :key="item.fieldValue"
              :label="item.fieldName"
              :value="item.fieldValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="训练名称："
          prop="trainingName"
          :rules="[{ required: true, message: '请输入训练名称'}]">
           <el-input v-model="form.trainingName" :maxlength="20" number-word style="width:95%;"></el-input>
        </el-form-item>
        <el-form-item  label="训练目标：">
           <el-input type="textarea" v-model="form.trainingAim" :maxlength="100" number-word style="width:95%;"></el-input>
        </el-form-item>
        <e-heading grade="2">重点领域</e-heading>
        <el-form-item  label="重点技术领域：">
          <el-checkbox-group v-model="form.techDomainInfo">
            <el-checkbox v-for="(item,index) in setData.TECHDOMAININFO" :key="index" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <custom-add-item
            v-if="isAddSet"
            v-model="setData.TECHDOMAININFO_CUSTOMGROUPVALUE"
            :isEdit="isEdit"
            :span="12"
            :simple-layout="true"
            :fixedData="setData.TECHDOMAININFO"
            :max-item="setData.MAX_CUSTOM_GROUP_NUM"
            :editState="true"
            :maxlength="setData.MAX_CUSTOM_MAX_LENGTH"
            repeatTipText="自定义项名称不能重复"
            placeholder="自定义重点技术领域"
            @change="handleCustomAddChange(setData.TECHDOMAININFO_CUSTOMGROUPVALUE, 'techDomainInfo')"/>
        </el-form-item>
        <el-form-item  label="重点精神领域：">
           <el-checkbox-group v-model="form.mindDomainInfo">
            <el-checkbox v-for="(item,index) in setData.MINDDOMAININFO" :key="index" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <custom-add-item
            v-if="isAddSet"
            v-model="setData.MINDDOMAININFO_CUSTOMGROUPVALUE"
            :isEdit="isEdit"
            :span="12"
            :simple-layout="true"
            :fixedData="setData.MINDDOMAININFO"
            :max-item="setData.MAX_CUSTOM_GROUP_NUM"
            :editState="true"
            :maxlength="setData.MAX_CUSTOM_MAX_LENGTH"
            repeatTipText="自定义项名称不能重复"
            placeholder="自定义重点精神领域"
            @change="handleCustomAddChange(setData.MINDDOMAININFO_CUSTOMGROUPVALUE, 'mindDomainInfo')"/>
        </el-form-item>
        <e-heading grade="2">具体信息</e-heading>
        <el-form-item  label="训练时长："
          prop="trainingDuration"
          :rules="[{ required: true, message: '请输入训练时长'}]">
           <el-input-number v-model="form.trainingDuration" :no-zero="true" :max="200" :min="1"/> 分钟
        </el-form-item>
        <el-form-item  label="教学教法：">
           <el-checkbox-group v-model="form.teachingInfo">
            <el-checkbox v-for="(item,index) in setData.TEACHINGINFO" :key="index" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <custom-add-item
            v-if="isAddSet"
            v-model="setData.TEACHINGINFO_CUSTOMGROUPVALUE"
            :isEdit="isEdit"
            :span="12"
            :simple-layout="true"
            :fixedData="setData.TEACHINGINFO"
            :max-item="setData.MAX_CUSTOM_GROUP_NUM"
            :editState="true"
            :maxlength="setData.MAX_CUSTOM_MAX_LENGTH"
            repeatTipText="自定义项名称不能重复"
            placeholder="自定义教学教法"
            @change="handleCustomAddChange(setData.TEACHINGINFO_CUSTOMGROUPVALUE, 'teachingInfo')"/>
        </el-form-item>
        <el-form-item  label="训练次数：">
           <el-input-number v-model="form.trainingTimes" :no-zero="true" :max="500" :min="0"/> 次
        </el-form-item>
        <el-form-item  label="训练强度：">
          <el-radio-group v-model="form.trainingIntension">
            <el-radio :label="0">低</el-radio>
            <el-radio :label="1">中</el-radio>
            <el-radio :label="2">高</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="技巧等级：">
          <el-radio-group v-model="form.skillLevel">
            <el-radio :label="0">初级</el-radio>
            <el-radio :label="1">中级</el-radio>
            <el-radio :label="2">高级</el-radio>
            <el-radio :label="3">顶级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="适用年龄：">
           <el-checkbox-group v-model="form.ageInfo">
            <el-checkbox v-for="(item,index) in setData.AGEINFO" :key="index" :label="item">{{item.label}}</el-checkbox>
            <el-checkbox label="setInput" style="margin-top:10px;" :disabled="!(setAge[0] && setAge[1])"><e-input-number-range v-model="setAge" :no-zero="true" :min="1" :max="30" @change="handleCheckAge($event)"/> 岁</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item  label="学员规模：" class="stud_num">
          <el-radio-group v-model="form.scopeInfo">
            <el-radio v-for="(item,index) in setData.SCOPEINFO" :key="index" :label="item">{{item.label}}</el-radio>
            <el-radio label="setInput" :disabled="!(setNum[0] && setNum[1])"><e-input-number-range v-model="setNum" :no-zero="true" :min="1" :max="100" @change="handleCheckScope($event)"/> 人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="场地规模：">
           <el-checkbox-group v-model="form.placeInfo">
            <el-checkbox v-for="(item,index) in setData.PLACEINFO" :key="index" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <custom-add-item
            v-if="isAddSet"
            v-model="setData.PLACEINFO_CUSTOMGROUPVALUE"
            :isEdit="isEdit"
            :span="12"
            :simple-layout="true"
            :fixedData="setData.PLACEINFO"
            :max-item="setData.MAX_CUSTOM_GROUP_NUM"
            :editState="true"
            :maxlength="setData.MAX_CUSTOM_MAX_LENGTH"
            repeatTipText="自定义项名称不能重复"
            placeholder="自定义场地规模"
            @change="handleCustomAddChange(setData.PLACEINFO_CUSTOMGROUPVALUE, 'placeInfo')"/>
        </el-form-item>
        <div class="line_fg"></div>
        <el-form-item  label="所需器材：">
          <el-input v-model="form.trainingTool" :maxlength="50" number-word style="width:95%;"></el-input>
        </el-form-item>
        <el-form-item  label="图示及描述：">
          <div :class="form.imageInfo.length > 0 ? 'img_card' : ''">
            <el-row class="img_cardlist" v-for="(item, index) in form.imageInfo" :key="index">
              <el-col :span="8">
                <span v-if="!item.value">暂无图示</span>
                <e-preview-box v-else>
                  <e-swiper height="210px" width="210px" :slides="1">
                    <e-swiper-item v-for="(sitem, sindex) in item.value" :key="sindex">
                        <img :src="sitem">
                    </e-swiper-item>
                  </e-swiper>
                </e-preview-box>
              </el-col>
              <el-col :span="16" style="padding:0 0 0 10px;line-height:2;">
                {{item.name}}
              </el-col>
              <p class="img_btn">
                <el-button type="link" size="small" @click="handleEditimgCard(item, index)">编辑</el-button>
                <el-button type="link" size="small" @click="handleRemoveimgCard(item, index)">删除</el-button>
              </p>
            </el-row>
            <p><el-button icon="plus" style="min-width:36px;" @click="handleAddimgcard" v-if="form.imageInfo.length < 5"></el-button></p>
          </div>
        </el-form-item>
        <el-form-item  label="进阶内容：">
           <el-input type="textarea" v-model="form.advancedContent" :maxlength="200" :rows="5" number-word style="width:95%;"></el-input>
        </el-form-item>
        <el-form-item  label="处理方式：">
           <el-input type="textarea" v-model="form.processMode" :maxlength="200" :rows="5" number-word style="width:95%;"></el-input>
        </el-form-item>
        <!--button-->
        <div class="button-box">
          <el-button @click="handleReset">取 消</el-button>
          <el-button @click="handlePreview">预 览</el-button>
          <el-button type="primary" native-type="submit" :loading="loading">确认提交</el-button>
        </div>
      </el-form>
    </div>
    <!--图片描述弹出层-->
    <el-dialog
      title="图示及描述"
      class="imgcard_dialog"
      :visible.sync="dialogVisible">
      <img-card @closeDialog="handleCloseDialog" @addImgcard="handlePushimgCard" :imgCardList="imgCardList" v-if="dialogVisible"></img-card> 
    </el-dialog>
  </div>
</template>

<script>
import { form } from 'utils/mixins' // 引入form mixin
import { ModeData } from './modeData'
import CustomAddItem from '../../../service/components/CustomAddItem'
import EInputNumberRange from '@e-ui/InputNumberRange'
import ImgCard from './components/ImgCard'
import { ESwiper, ESwiperItem } from '@e-ui/swiper'
import api from 'api/trainingProgram'
import { mapGetters } from 'vuex'
import { cloneObj, cmpareArray } from 'utils/index'
export default {
  mixins: [form],
  components: {
    CustomAddItem,
    EInputNumberRange,
    ImgCard,
    ESwiper,
    ESwiperItem
  },
  computed: {
    ...mapGetters({
      mode_sport_list: 'mode_sport_list'
    })
  },
  created () {
    this.$store.dispatch('mode_sport_list', '')
  },
  mounted () {
    window.onbeforeunload = function (e) {
      e = window.event || e
      return false
      // e.returnValue = ('确定离开当前页面吗？')
    }
    if (this.$route.query.id) { // 编辑时获取默认数据
      this.isEdit = true
      let arrayCode = ['techDomainInfo', 'mindDomainInfo', 'teachingInfo', 'ageInfo', 'placeInfo']
      let setObj = {
        techDomainInfo: 'TECHDOMAININFO',
        mindDomainInfo: 'MINDDOMAININFO',
        teachingInfo: 'TEACHINGINFO',
        ageInfo: 'AGEINFO',
        placeInfo: 'PLACEINFO'
      }
      api.addTrainStyle({id: Number(this.$route.query.id)}, {type: 'GET'}).then((res) => {
        if (res.data) {
          for (let key in this.form) {
            if (arrayCode.includes(key)) { // 多选数组
              let val = []
              let setVal = []
              let getArray = res.data[key].split(';')
              let value = []
              let scope = this
              this.setData[setObj[key]].forEach((item, index) => {
                if (getArray.includes(item.name) || getArray.includes(item.label)) {
                  val.push(item)
                  value.push(item.name || item.label)
                }
              })
              getArray.forEach((item, index) => {
                if (!value.includes(item)) {
                  if (key === 'ageInfo') { // 适用年龄
                    if (item) {
                      setVal.push('setInput')
                      scope.setAge = item.split('-')
                    }
                  } else {
                    setVal.push({
                      name: item,
                      value: 1,
                      checked: !!item
                    })
                  }
                }
              })
              if (setVal.length > 0) { // 有自定义值
                this.setData[setObj[key] + '_' + 'CUSTOMGROUPVALUE'] = setVal
              } else { // 无自定义值
                this.setData[setObj[key] + '_' + 'CUSTOMGROUPVALUE'] = [{name: '', value: 1, checked: false}]
              }
              this.$set(this.form, key, val.concat(setVal))
            } else if (key === 'scopeInfo') { // 学员规模
              let scope = this
              let isUserSet = []
              this.setData.SCOPEINFO.forEach((item, index) => {
                if (res.data[key]) {
                  if (item.name === res.data[key]) {
                    scope.$set(scope.form, key, item)
                    isUserSet.push(true)
                  }
                }
              })
              if (!isUserSet.includes(true) && res.data[key]) {
                scope.$set(scope.form, key, 'setInput')
                scope.setNum = res.data[key].split('-')
              }
            } else { // 其他
              this.$set(this.form, key, res.data[key])
            }
          }
          this.isAddSet = true
          if (cmpareArray(this.setAge, [1, 1])) {
            this.setAge = [0, 0]
          }
          if (cmpareArray(this.setNum, [1, 1])) {
            this.setNum = [0, 0]
          }
        }
      })
    } else {
      this.isAddSet = true
      if (cmpareArray(this.setAge, [1, 1])) {
        this.setAge = [0, 0]
      }
      if (cmpareArray(this.setNum, [1, 1])) {
        this.setNum = [0, 0]
      }
    }
  },
  destroyed () {
    window.onbeforeunload = null
  },
  data () {
    return {
      loading: false, // 必需要返回loading
      isEdit: false,
      isAddSet: false,
      setData: cloneObj(ModeData),
      dialogVisible: false,
      setAge: [0, 0],
      setNum: [0, 0],
      imgCardList: {
        value: [],
        name: ''
      },
      imgCardIndex: '',
      form: {
        sportType: '',
        trainingName: '',
        trainingAim: '',
        techDomainInfo: [],
        mindDomainInfo: [],
        trainingDuration: 0,
        teachingInfo: [],
        trainingTimes: 0,
        trainingIntension: '',
        skillLevel: '',
        ageInfo: [],
        scopeInfo: {},
        placeInfo: [],
        trainingTool: '',
        imageInfo: [],
        advancedContent: '',
        processMode: ''
      }
    }
  },
  methods: {
    getSubmitData () {
      let subData = {}
      for (let key in this.form) {
        subData[key] = this.form[key]
      }
      for (let key in subData) {
        if (key === 'scopeInfo') { // 处理学员规模自定义输入项
          if (JSON.stringify(subData[key]) === '{}') {
            delete subData[key]
          }
          if (subData[key] === 'setInput') {
            subData[key] = {
              label: this.setNum.join('-') + '人',
              name: this.setNum.join('-'),
              value: 1
            }
          }
        } else if (key === 'ageInfo') { // 适用年龄
          let scope = this
          subData[key].forEach((item, index) => {
            if (item === 'setInput') {
              if (scope.setAge.join('-') === '0-0') { // 为空不转
                subData[key] = []
              } else {
                subData[key][index] = {
                  label: scope.setAge.join('-') + '岁',
                  name: scope.setAge.join('-'),
                  value: 1
                }
              }
            }
          })
        }
      }
      return subData
    },
    submit () { // 提交后台数据
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let subData = this.getSubmitData()
          let type = this.$route.query.id ? 'PUT' : 'POST'
          if (this.$route.query.id) {
            subData.id = this.$route.query.id
          }
          api.addTrainStyle(JSON.stringify(subData), {context: this, type: type}).then((res) => {
            let state = '2'
            if (localStorage.getItem('role_type') === '99') { // 根据不用权限跳至不同TAB 管理员-2（已通过）教练（99）-0（待审核）
              state = '0'
            }
            this.$router.push({path: '/training/trainingprogram/mode', query: {auditStatus: state}})
          })
        } else {
          return false
        }
      })
    },
    handleCustomAddChange (setVal, formName) { // 自定义项处理
      let setData = []
      let userData = []
      this.form[formName].forEach((item, index) => { // 默认选择项
        if (item.value === 0) {
          userData.push(item)
        }
      })
      setVal.forEach((item, index) => { // 自定义选择项
        if (item.name) {
          setData.push({
            name: item.name.replace(/;/g, ''),
            value: 1
          })
        }
      })
      this.form[formName] = userData.concat(setData)
    },
    handleAddimgcard () { // 新增图片及描述
      this.imgCardList = {
        value: [],
        name: ''
      }
      this.imgCardIndex = ''
      this.dialogVisible = true
    },
    handleCloseDialog () { // 关闭弹窗
      this.dialogVisible = false
    },
    handlePushimgCard (val) { // push图片及描述
      this.dialogVisible = false
      if (this.imgCardIndex !== '') {
        this.form.imageInfo.splice(this.imgCardIndex, 1, val)
      } else {
        this.form.imageInfo.push(val)
      }
    },
    handleEditimgCard (val, index) { // edit图片及描述
      this.imgCardList = val
      this.imgCardIndex = index
      this.dialogVisible = true
    },
    handleRemoveimgCard (val, index) { // delete图片及描述
      this.$confirm('删除后将不可恢复，确认删除该图示及描述吗？', '温馨提示', {type: 'warning'}).then(() => {
        this.form.imageInfo.splice(index, 1)
      })
    },
    handleReset () { // 取消编辑
      this.$confirm('训练方式还未提交，确定要放弃编辑吗？', '温馨提示', {type: 'warning'}).then(() => {
        let scope = this
        setTimeout(() => {
          scope.$router.push({path: '/training/trainingprogram/mode'})
        }, 600)
      })
    },
    handlePreview () { // 预览
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let subData = this.getSubmitData()
          localStorage.setItem('mode_list', JSON.stringify(subData))
          window.open('/training/trainingprogram/mode/show')
        } else {
          return false
        }
      })
    },
    handleCheckAge (val) { // 年龄区间重复校验
      let valStr = val.join('-')
      this.setData.AGEINFO.forEach((item, index) => {
        if (item.name === valStr) {
          val[0] = 0
          val[1] = 0
          this.$message.error('已有该年龄段，请重新设置')
        }
      })
    },
    handleCheckScope (val) { // 学员规模重读校验
      let valStr = val.join('-')
      this.setData.SCOPEINFO.forEach((item, index) => {
        if (item.name === valStr) {
          val[0] = 0
          val[1] = 0
          this.$message.error('已有该人数范围，请重新设置')
          this.form.scopeInfo = ''
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.addmode_form{
  margin:30px 0 0 0;
  .line_fg{
    line-height:1px;
    height:1px;
    background:#e3e3ec;
    margin: 50px 0;
  }
  .input-number-range{
    width:120px;
  }
  .heading-2{
    margin:35px 0;
  }
  .img_card{
    border-radius:4px;
    border:1px solid #e3e3ec;
    padding:10px;
    width:95%;
  }
  .el-carousel__item{
    .slide_img{
      border:1px solid #e3e3ec;
      img{
        vertical-align:middle;
      }
    }
  }
}
</style>
<style lang="scss">
.addmode_form{
  .custom-group-wrapper{
    margin-top:10px;
    .xcheckbox-item .xsmall{
      width:95%!important;
    }
  }
  .stud_num{
    .el-form-item__label{
      padding:13px 12px 13px 0;
    }
  }
  .custom-group-wrapper{
    .err-tips-wrapper{
      left:-120px!important;
    }
  }
}
.imgcard_dialog{
  .el-dialog--small{
    width:860px;
  }
}
.img_cardlist{
  margin-bottom:10px;
  padding-bottom:30px;
  border-bottom:1px solid #e3e3ec;
  position:relative;
  .img_btn{
    position:absolute;
    right:5px;
    bottom:-15px;
    font-size:12px;
  }
  .el-carousel__button{
    width:10px;
  }
}
</style>
